package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import database.DatabaseManager;

/**
 * Servlet implementation class EditArticleServlet
 */
public class EditArticleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditArticleServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    private void editArticle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("utf-8");
    	int articleID = Integer.parseInt(request.getParameter("articleID"));
    	String title = request.getParameter("title");
    	String content = request.getParameter("content");
    	if(title != null && !title.equals("")) {
    		boolean b = DatabaseManager.articleChangeTitle(articleID, title);
    		if(!b) {
    			//do nothing
    		}
    	}
    	
    	PrintWriter out = new PrintWriter(request.getSession().getServletContext().getRealPath("/") + "/file/" + articleID);
    	out.print(content);
    	out.close();
    	response.sendRedirect(request.getContextPath() + "/article.jsp?articleID=" + articleID);
    }

    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.editArticle(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.editArticle(request, response);
	}

}
